var mongoose=require('mongoose');
const Sort=require('../models/sort.model');
exports.create=function(req,res,next){
    const sort=new Sort(req.body);
    sort.save().then(data=>{
        res.json(data)
    })
};
exports.updata=function(req,res,next){
    const id=req.params.id;
    Sort.findByIdAndUpdate(id,{$set:req.body},{new:false}).then(data=>{
        res.json(data)
    });
}
exports.remove=function(req,res,next){}

exports.list=function(req,res,next){
    console.log(+req.params.type);
    var type=+req.params.type||1;
    Sort.find({type:type},(err,data)=>{
        res.json(reverseTree(data,null))
     
    })
}
function reverseTree(data,pid){
    var result=[],temp;
    var data=JSON.parse(JSON.stringify(data));
    for(var i in data){
        if(data[i].parentId===pid){
            result.push(data[i]);
            temp=reverseTree(data,data[i]._id);
            if(temp.length>0){
                data[i].children=temp;
            }
        }
    }
    return result;
}
exports.getdata=function(req,res,next){
    const id=req.params.id;
    Sort.findById(id,(err,data)=>{
        res.json(data);
        // console.log(data)
    })
}